package cn.hadron.ssh.dao.impl;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import cn.hadron.ssh.bean.User;
import cn.hadron.ssh.dao.UserDao;
public class UserDaoImpl implements UserDao {
	private SessionFactory sessionFactory;
	private Session session;

	@Override
	public void save(User u) {
		getSession().beginTransaction();
		getSession().save(u);
		getSession().getTransaction().commit();
	}
	@Override
	public void update(User u) {
		getSession().beginTransaction();
		getSession().update(u);
		getSession().getTransaction().commit();
	}
	@Override
	public void delete(int id) {
		getSession().beginTransaction();
		User u = (User) getSession().load(User.class, id);
		getSession().delete(u);
		getSession().getTransaction().commit();
	}

	// 查询不需要事务处理
	@Override
	public User load(Integer id) {
		return (User)getSession().load(User.class, id);
	}
	@Override
	public User findUser(String username) {
		User u = getSession().createQuery("from User where username=?", User.class)
				.setParameter(0, username).uniqueResult();
		return u;
	}
	@Override
	public User findUser(String username, String password) {
		String hql = "from User where username=? and password=?";
		User u = getSession().createQuery(hql, User.class).setParameter(0, username)
				.setParameter(1, password).uniqueResult();
		return u;
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Session getSession() {
		if (null == session || false == session.isOpen())
			session = sessionFactory.openSession();
		return session;
	}

	public void setSession(Session session) {
		this.session = session;
	}
}
